package com.boss.thirteen.controller;

import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.util.DateUtils;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.framework.exception.AppRuntimeException;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.service.IAgencySalaryService;
import com.boss.salary.vo.AgencySalaryVO;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import com.boss.thirteen.entity.SalaryThirteenMonth;
import com.boss.thirteen.entity.ThirteenAgencyVerify;
import com.boss.thirteen.service.ISalaryThirteenMonthEndService;
import com.boss.thirteen.service.IThirteenMouldService;
import com.boss.thirteen.service.impl.ThirteenSalaryExcelServiceImpl;
import com.boss.thirteen.vo.ThirteenMouldVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/thirteenSalary")
public class ThirteenSalaryController extends BasicinfoBaseController {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(ThirteenSalaryController.class);

    @Autowired
    private IThirteenMouldService thirteenMouldService;
    @Autowired
    private ISalaryThirteenMonthEndService salaryThirteenMonthEndService;
    @Autowired
    private ThirteenSalaryExcelServiceImpl writeSalaryReportExcel;
    @Autowired
    private IAgencySalaryService service;


    /**
     * 查询 十三月工资模板分页
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/queryThirteenSalaryMouldPage")
    public ApiResultDTO queryThirteenSalaryMouldPage(@RequestHeader("X-Token") String tokenid,
                                                @RequestParam(value = "page") String page,
                                                @RequestParam(value = "limit") String limit,
                                                @RequestParam(value = "year") String year) {
        try {
            UserDTO userDTO = getUser(tokenid);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            if(StringUtils.isEmpty(year)) {
                year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            }
            PageDTO<Map<String,Object>> pageDTO = thirteenMouldService.querySalaryThirteenMouldPage(paginationDTO,year,userDTO.getProvince());
            return ApiResultDTO.success(pageDTO,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询异常");
        }
    }

    /**
     * 查询 十三月工资模板单位
     * @param
     * @param
     * @return
     */
    @GetMapping("/queryThirteenSalaryAgency")
    public ApiResultDTO queryThirteenSalaryAgencyIds(@RequestHeader("X-Token") String tokenid,
                                                     @RequestParam(value = "year") String year) {
        try {
            UserDTO userDTO = getUser(tokenid);
            if(StringUtils.isEmpty(year)) {
                year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            }
            Map<String,Object> params= new HashMap<>();
            params.put("mof_div_code",userDTO.getProvince());
            params.put("year",year);
            List<ThirteenAgencyVerify> agencyIds = thirteenMouldService.queryThirteenAgency(params);
            return ApiResultDTO.success(agencyIds,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询异常");
        }
    }

    /**
     * 新增 工资类型基础数据
     * @param tv
     * @return
     */
    @PostMapping("/saveThirteenSalaryMould")
    public ApiResultDTO saveThirteenSalaryMould(@RequestHeader("X-Token") String tokenid,
                                                @RequestBody ThirteenMouldVO tv) {
        try {
            String mouldKey= SysUtils.generateGuid();//mouldKey同模板key相同
            String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            UserDTO userDTO = getUser(tokenid);
            for(String agencgId:tv.getAgencyIds()){
                String uuid= SysUtils.generateGuid();
                ThirteenAgencyVerify tav=new ThirteenAgencyVerify();
                tav.setId(uuid);
                tav.setBizKey(uuid);
                tav.setMouldKey(mouldKey);
                tav.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
                tav.setAgencyId(agencgId);
                tav.setIsWorkflowInit(SystemDictConstant.IS_FALSE);
                tav.setMofDivCode(userDTO.getProvince());
                tav.setYear(year);
                tav.setIsDeleted(SystemDictConstant.NOT_DELETED);
                tv.getThirteenAgencyVerify().add(tav);
            }
            for(Map<String,Object> map:tv.getMoulds()){
                map.put("mouldKey",mouldKey);
                map.put("mof_div_code",userDTO.getProvince());
                map.put("year",year);
            }
            thirteenMouldService.insertMould(tv.getThirteenAgencyVerify(),tv.getMoulds(),userDTO);
            return ApiResultDTO.success(null, "保存成功");
        } catch (Exception e) {
            logger.error("新增 十三月工资模板异常", e);
            return ApiResultDTO.error(ERROR_RSCODE,  e.getMessage());
        }
    }

    /**
     * 更新 十三月工资模板
     * @param tv
     * @return
     */
    @PostMapping("/updateThirteenSalaryMould")
    public ApiResultDTO updateThirteenSalaryMould(@RequestHeader("X-Token") String tokenid,
                                                  @RequestBody ThirteenMouldVO tv) {
        try {
            UserDTO userDTO = getUser(tokenid);
            String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
            for(Map<String,Object> map:tv.getMoulds()){
                map.put("mof_div_code",userDTO.getProvince());
                map.put("year",year);
            }

            thirteenMouldService.updateMould(tv);
            return ApiResultDTO.success(null, "更新成功");
        } catch (Exception e) {
            logger.error("更新 十三月工资模板", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 删除十三月工资模板
     * @param mouldKey
     * @return
     */
    @DeleteMapping("/deleteThirteenMould/{mouldKey}")
    public ApiResultDTO deleteThirteenMould(@RequestHeader("X-Token") String tokenid,
                                            @PathVariable("mouldKey") String mouldKey) {
        try {
            thirteenMouldService.deleteMould(mouldKey);
            return ApiResultDTO.success();
        } catch (Exception e) {
            logger.error("删除十三月工资模板异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 查询 十三月工资模板单位
     * @param
     * @param
     * @return
     */
    @GetMapping("/getNotAddPerosn")
    public ApiResultDTO getNotAddPerosn(@RequestHeader("X-Token") String tokenid,
                                        @RequestParam(value = "agencyId") String agencyId) {
        try {
            UserDTO userDTO = getUser(tokenid);
            List<SalaryThirteenMonth> salaryThirteenMonths = salaryThirteenMonthEndService.selectSalaryThirteenPersonFromHistory(agencyId,userDTO.getProvince());
            return ApiResultDTO.success(salaryThirteenMonths,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询异常");
        }
    }
    /**
     * 删除十三月工资模板
     * @param stms
     * @return
     */
    @PostMapping("/addThirteenMonth")
    public ApiResultDTO addThirteenMonth(@RequestBody List<SalaryThirteenMonth> stms) {
        try {
            salaryThirteenMonthEndService.addSalaryThirteenMonth(stms);
            return ApiResultDTO.success();
        } catch (Exception e) {
            logger.error("删除十三月工资模板异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }
    /**
     * 删除十三月工资模板
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteThirteenMonth/{ids}")
    public ApiResultDTO deleteThirteenMonth(@RequestHeader("X-Token") String tokenid,
                                            @PathVariable("ids") List<String> ids) {
        try {
            salaryThirteenMonthEndService.deleteThirteenMonth(ids);
            return ApiResultDTO.success();
        } catch (Exception e) {
            logger.error("删除十三月工资模板异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     * 编报
     * @param data
     * @return
     */
    @PostMapping("/submitUnitSalaryReportData")
    public ApiResultDTO submitUnitSalaryReportData(@RequestBody List<SalaryThirteenMonth> data){
        try{
            salaryThirteenMonthEndService.batchUpdateSalaryThirteenMonth(data);
            return ApiResultDTO.success();
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "保存 单位工资编报数据发生异常");
        }
    }
    /**
     * 动态查询工资编报表头
     * @param agencyId
     * @return
     */
    @GetMapping("/queryColumnName")
    public ApiResultDTO queryColumnName(@RequestHeader("X-Token") String tokenid,@RequestParam(value = "agencyId") String agencyId,@RequestParam Map<String,Object> condition){
        try{
            UserDTO userDTO = getUser(tokenid);
            List<String> columnNameList = salaryThirteenMonthEndService.getColumnName(agencyId,condition,userDTO,true);
            return ApiResultDTO.success(columnNameList);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败");
        }
    }
    /**
     * 分页查询 单位工资编报数据
     * @param page 页码
     * @param limit 行数
     * @param flag 判断tab页
     * @param agencyId 机构ID
     * @param condition 查询条件
     * @return
     */
    @GetMapping("/queryUnitSalaryReportPage")
    public ApiResultDTO queryUnitSalaryReportPage(@RequestHeader("X-Token") String tokenid,
                                                  @RequestParam(value = "page") String page,
                                                  @RequestParam(value = "limit") String limit,
                                                  @RequestParam(value = "flag") String flag,
                                                  @RequestParam(value = "agencyId") String agencyId,
                                                  @RequestParam(value = "menuId") String menuId,
                                                  @RequestParam Map<String,Object> condition) {
        try{
            UserDTO userDTO = getUser(tokenid);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            PageDTO<SalaryThirteenMonth> pageDTO = salaryThirteenMonthEndService.getUnitSalaryReportPage(paginationDTO, agencyId, flag, condition,userDTO,menuId,tokenid);
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }
    }

    /**
     *
     * @param tokenid
     * @param page
     * @param limit
     * @param flag
     * @param menuId
     * @return
     */
    @GetMapping("/getVerifySalaryData")
    public ApiResultDTO getVerifySalaryData(@RequestHeader("X-Token") String tokenid,
                                            @RequestParam(value = "page") String page,
                                            @RequestParam(value = "limit") String limit,
                                            @RequestParam(value = "flag") String flag,
                                            @RequestParam(value = "agencyId") String agencyId,
                                            @RequestParam(value = "menuId") String menuId,
                                            @RequestParam(value = "bank",required = false) String bank){
        try{
            UserDTO userDTO = getUser(tokenid);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            Map<String,Object> otherParams=new HashMap<>();
            otherParams.put("province",userDTO.getProvince());
            otherParams.put("bank",bank);
            PageDTO<Map<String,Object>> pageDTO = salaryThirteenMonthEndService.getVerifySalaryData(paginationDTO, agencyId, flag,userDTO,menuId,otherParams,tokenid);
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }

    }
    @GetMapping("/queryAgencySubmitStatus")
    public ApiResultDTO queryAgencySubmitStatus(@RequestHeader("X-Token") String tokenid,
                                            @RequestParam(value = "page") String page,
                                            @RequestParam(value = "limit") String limit,
                                            @RequestParam(value = "flag") String flag,
                                            @RequestParam(value = "menuId") String menuId){
        try{
            UserDTO userDTO = getUser(tokenid);
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page, limit);
            PageDTO<ThirteenAgencyVerify> pageDTO = salaryThirteenMonthEndService.queryAgencySubmitStatus(paginationDTO, flag,userDTO,menuId,tokenid);
            return ApiResultDTO.success(pageDTO);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        }

    }

    /**
     * 单位工资编报导出
     * @return
     */
    @GetMapping("/outPutSalaryReportList")
    public ApiResultDTO outPutSalaryReportList( @RequestHeader("X-Token") String tokenid,
                                                @RequestParam(value = "agencyId") String agencyId,
                                                HttpServletResponse response){
        try {
            UserDTO userDTO = getUser(tokenid);
            String fileName = "单位工资编报";
            OutputStream outputStream = getOutputStream(fileName,response);
            writeSalaryReportExcel.writeExcel03(agencyId,userDTO,outputStream);
            return ApiResultDTO.success();
        } catch (Exception e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "导出失败");
        }
    }

    /**
     * 单位工资编报导入
     * @return
     */
    @PostMapping("/ImportSalaryReportListAsync")
    public ApiResultDTO ImportSalaryReportListAsync(@RequestHeader("X-Token") String tokenid,
                                                    @RequestParam("file") MultipartFile file,
                                                    @RequestParam(value = "agencyId") String agencyId){
        try {
            UserDTO userDTO = getUser(tokenid);

            List<AgencySalaryVO> exccelColumnName = service.getExccelColumnName(userDTO);
            String province = userDTO.getProvince();
            Map<String,String> remap=writeSalaryReportExcel.ReadAsync(file, province, agencyId, exccelColumnName);
            return ApiResultDTO.success(remap);
        } catch (AppRuntimeException e){
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "导入失败"+e.getMessage());
        }

    }

    /**
     * 获取单位总发放人数，金额，人员变动数
     * @return
     */
    @GetMapping("/queryThirteenChangeCount")
    public ApiResultDTO queryThirteenChangeCount(@RequestHeader("X-Token") String tokenid,
                                                 @RequestParam(value = "agencyId") String agencyId){
        try {
//            UserDTO userDTO = getUser(tokenid);
            Map<String,Object> remap=salaryThirteenMonthEndService.queryThirteenCount(agencyId);
            return ApiResultDTO.success(remap);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败"+e.getMessage());
        }

    }


    /**
     * 获取单位增减人员信息
     * @return
     */
    @GetMapping("/queryThirteenChangePerson")
    public ApiResultDTO queryThirteenChangePerson(@RequestHeader("X-Token") String tokenid,
                                                 @RequestParam(value = "agencyId") String agencyId){
        try {
//            UserDTO userDTO = getUser(tokenid);
            List<Map<String,Object>> list=salaryThirteenMonthEndService.queryThirteenChangePersonInfo(agencyId);
            return ApiResultDTO.success(list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "查询失败"+e.getMessage());
        }

    }
    /**
     * 导出文件时为Writer生成OutputStream
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws AppRuntimeException {
        //创建本地文件
        fileName = fileName + ".xls";

        try {
            fileName = new String(fileName.getBytes(), "UTF-8");
            response.addHeader("Content-Disposition", "filename=" + fileName);

            return response.getOutputStream();
        } catch (Exception e) {

            throw new AppRuntimeException("下载失败");
        }
    }



}

